import pymysql
from loguru import logger
from pydantic import BaseModel

class DBOptions(BaseModel):
    host: str = 'localhost'
    port: int = 3306
    user: str = 'root'
    passwd: str = 'sa'
    db: str = 'ectypal'
    charset: str = 'utf8'

class DBPool(object):

    def __init__(self, options: DBOptions):
        """
        sample options: {
            'host': 'localhost',
            'port': 3306,
            'user': 'root',
            'passwd': 'sa',
            'db': 'ectypal',
            'charset': 'utf8'
        }
        :param options:
        """
        self.options = options
        logger.debug('开始连接数据库：\n{}'.format(self.options.json()))
        self.__conn = pymysql.connect(**self.options.dict())
        self.__cursors = self.__conn.cursor(cursor=pymysql.cursors.DictCursor)
        msg = r'数据库连接成功:{}'.format(self.options.db)
        logger.debug(msg)

    def close(self):
        if self.__conn:
            if self.__cursors:
                self.__cursors.close()
            self.__conn.close()
        msg = r'数据库已断开:{}'.format(self.options.db)
        logger.debug(msg)

    def query(self, sql, args):
        logger.debug(r'> {}'.format(sql % args))
        self.__conn.ping(reconnect=True)
        self.__cursors.execute(sql, args)
        data = self.__cursors.fetchall()
        return data

def db_pool(options: DBOptions) -> DBPool:
    return DBPool(options)

if __name__ == '__main__':
    pool = db_pool(DBOptions(
        host = 'localhost',
        port = 3306,
        user = 'root',
        passwd = 'sa',
        db = 'ectypal',
        charset = 'utf8'
    ))
    pool.query('select * from stylesheet01;',())
    pool.close()